package com.bstek.uflo.form.view.table.dialect.impl;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.bstek.uflo.form.Constants;
import com.bstek.uflo.form.model.TableColumn;
import com.bstek.uflo.form.model.TableDefinition;

/**
 * @author Jacky.gao
 * @since 2013年11月7日
 */
@Component("com.bstek.uflo.form.view.table.dialect.impl.MySqlDialect")
public class MySqlDialect extends AbstractDialect {

	public boolean support(Connection connection) {
		return support(connection, "mysql", null);
	}

	public String[] generateCreateTableSchema(TableDefinition table) {
		String sql=generateSchema(table, false);
		List<TableDefinition> children=table.getSlaveTables();
		if(children!=null && children.size()>0){
			TableDefinition child=children.get(0);
			return new String[]{sql,generateSchema(child,true)};
		}
		return new String[]{sql};
	}
	
	public String getPaginationSql(String sql, int pageNo, int pageSize) {
		int startNo = (pageNo - 1) * pageSize;
		return sql + " limit " + startNo + "," + pageSize;
	}
	
	private String generateSchema(TableDefinition table,boolean isChildren){
		StringBuffer sb=new StringBuffer();
		sb.append("create table "+table.getName()+"(");
		List<TableColumn> columns=table.getColumns();
		if(columns!=null){
			sb.append(Constants.PRIMARY_KEY_COLUMN+" bigint primary key,");
			for(TableColumn col:columns){
				sb.append(col.getName()+" "+col.getDataType() +(col.isEmpty()?"":" not null"));									
				sb.append(",");
			}
			if(isChildren){
				sb.append(""+Constants.MASTER_ID+" bigint,");
			}else{
				sb.append(""+Constants.PROCESS_PROMOTER+" varchar(60),");								
			}
			sb.append(""+Constants.STATE_COLUMN+" varchar(20)");
		}
		sb.append(")ENGINE=InnoDB DEFAULT CHARSET=gbk;");			
		return sb.toString();
	}
	
	public List<String> getDataTypes() {
		List<String> list=new ArrayList<String>();
		list.add("Varchar(30)");
		list.add("Date");
		list.add("Integer");
		list.add("SmallInt");
		list.add("Double");
		list.add("Float");
		return list;
	}
}
